<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="授权管理"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @sort-change="sortChange"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" icon="Plus" type="primary" @click="addAgvFn"> 新增 </el-button>
      </template>
      <template #createBy="{ row }"> {{ row.modifiedByName ? row.modifiedByName : row.createByName }} </template>
      <template #featureList="{ row }">
        {{ (row.featureList && defaultFeature.concat(row.featureList).join(",")) || "--" }}
      </template>
      <template #authType="{ row }">
        {{ row.expireTime ? "非永久" : "永久" }}
      </template>

      <template #expireTime="{ row }">
        <span :class="{ red: new Date(row.expireTime).getTime() < new Date().getTime() }">{{ row.expireTime }}</span>
      </template>
      <!-- 表格操作 -->
      <template #operation="{ row }">
        <el-button v-auth="'get'" type="primary" link @click="detailAuthFn(row.id)"> 查看 </el-button>
        <el-button v-auth="'update'" type="primary" link @click="downFilesOpen(row.licenseFilePath, 'license.lic')">
          下载许可
        </el-button>
        <el-button v-auth="'update'" type="primary" link @click="editAgvFn(row)"> 更新授权 </el-button>
        <el-button v-auth="'delete'" type="primary" link @click="deleteAccount(row)"> 删除 </el-button>
      </template>
    </ProTable>
    <ImportExcel ref="dialogRef" />
    <div v-if="drawerVisible">
      <Dialog v-model:drawerVisible="drawerVisible" v-model:config="config" @change="refresh" class-name="dialog-form-custom">
        <template #applicationFilePath="{ scope }">
          <div class="upload-flex">
            <el-input :readonly="true" :value="scope?.applicationFilePath[0]?.originalFileName" />
            <el-button type="primary" :icon="Plus"></el-button>
          </div>
        </template>
        <template #featureList="{ scope }">
          <el-checkbox-group v-model="scope.featureList">
            <el-checkbox
              v-for="(item, index) in getDict('authFeature')"
              :value="item.value"
              name="type"
              :key="'featureList_' + index"
              :disabled="defaultFeature.includes(item.value)"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </Dialog>
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue"; // onMounted getCurrentInstance
import { Plus } from "@element-plus/icons-vue";
import { User } from "@/api/interface"; //Dict
import { useHandleData } from "@/hooks/useHandleData";
import { downFilesOpen } from "@/utils/index";
// import { useDownload } from "@/hooks/useDownload";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
//import { ElMessage } from "element-plus"; // ElMessageBox
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import Dialog from "@/components/DialogForm/index.vue";
// import { genderType } from "@/utils/serviceDict"; // userStatus
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getListAllUser } from "@/api/modules/sys"; // exportUserInfo,BatchAddUser getDict getParamByParentIdList,
import {
  getCompanyAuthorizePage,
  addCompanyAuthorize,
  updateCompanyAuthorize,
  deleteCompanyAuthorize,
  getCompanyAuthorizeDetail,
  getProjectListCode
} from "@/api/modules/project";
import { useDict } from "@/hooks/useDict";
import { getCompanyList } from "@/api/modules/customer";
import { AUTHORIZE } from "@/constants";
const authTypeList = [
  {
    name: "永久",
    id: 1
  },
  {
    name: "非永久",
    id: 2
  }
];
// hook
const { getDict } = useDict(["orderType", "businessType", "orderStatus", "productionFactory", "authFeature"]); // getDictItem
// 变量
// businessType.value = ;
// console.log(businessType.value);
// let userInfo = ref({});
// const cxt = getCurrentInstance();
// const dict = cxt?.appContext.config.globalProperties.$dict;

// 跳转详情页
// const toDetail = () => {
//   router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
// };
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });
let drawerVisible = ref(false);
let config = ref<any>({
  width: 60
});
let companyList = reactive([]);
const listAllUser = ref<any>([]);
const sortOptions = ref<any>({
  sortFiled: undefined,
  sortTyp: undefined
});
// computed
// const userInfos = computed(() => id => {
//   return listAllUser.value.find(item => item.id == id);
// });
// 方法
// 获取全部公司
const getCompanyListFn = async () => {
  const { data } = await getCompanyList();
  companyList = data || [];
  return companyList;
};
// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  listAllUser.value = data;
};

// 获取所有项目
const projectList: any = ref([]);
const getProject = async () => {
  const { data } = await getProjectListCode();
  projectList.value = data || [];
};
// 获取字典数据
// const getDicList = async (params: Dict.ResDictList) => {
//   const { data } = await getParamByParentIdList(params);
//   return data || [];
// };
// 转换显示
// const conversionDisplay = (id: string, type: string) => {
//   const listItem = dictList[type]?.find(item => item.id === id);
//   return listItem?.name;
// };
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: Number(data.total)
  };
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  const newParams: any = {
    currentPage: params.pageNum,
    searchKey: params.searchKey ?? undefined,
    isPermanent: params.authType === 2 ? false : params.authType === 1 ? true : undefined
  };

  return getCompanyAuthorizePage({ ...newParams, ...sortOptions.value });
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
// const { BUTTONS } = useAuthButtons();
// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
//   return <el-button type="primary">{column.label}</el-button>;
// };
// 表格配置项
const columns: ColumnProps<User.ResUserList>[] = [
  { type: "selection", fixed: "left", width: 80, props: { selectable: false } },
  {
    prop: "id",
    label: "ID",
    isShow: false
  },
  {
    prop: "licenseName",
    label: "授权名称",
    search: { el: "input", label: "授权名称", key: "searchKey" }
  },
  {
    prop: "projectName",
    label: "订单编号"
  },
  {
    prop: "companyName",
    label: "客户名称"
  },

  {
    prop: "featureList",
    label: "产品许可"
  },
  {
    prop: "agvNums",
    label: "AGV数量"
    // search: { el: "select", label: "订单类型", key: "typeId", props: { filterable: true } },
    // enum: async () => await getDictAsync("orderType"),
    // fieldNames: { label: "name", value: "id" }
  },
  {
    prop: "authType",
    label: "授权类型",
    search: { el: "select", label: "授权类型", key: "authType", props: { filterable: true } },
    enum: authTypeList,
    fieldNames: { label: "name", value: "id" }
    // isShow: false
  },
  {
    prop: "gmtCreate",
    label: "签发时间",
    sortable: "custom"
  },
  {
    prop: "expireTime",
    label: "过期时间",
    sortable: "custom"
  },
  {
    prop: "createBy",
    label: "签发用户"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 300 }
];

// 删除
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteCompanyAuthorize, { id: params.id }, `删除【${params.licenseName}】`);
  proTable.value?.getTableList();
};

const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);

const defaultFeature = ["RDS"];
const addAgvFn = () => {
  drawerVisible.value = true;
  config.value.title = "新增授权";
  config.value.show = false;
  config.value.form = {
    formData: {
      licenseName: "",
      companyId: "",
      companyName: "",
      projectId: "",
      projectName: "",
      applicationFilePath: [],
      agvNums: "",
      expireTime: "",
      featureList: defaultFeature
    },
    rules: {
      licenseName: [{ required: true, message: "请填写授权名称" }],
      applicationFilePath: [{ required: true, message: "请上传申请文件" }]
    }
  };
  config.value.column = [
    {
      type: "group",
      title: "",
      direction: "",
      list: [
        {
          type: "input",
          key: "licenseName",
          formItemAttribute: {
            label: "授权名称"
          },
          attributes: {
            placeholder: "请填写授权名称"
          }
        },
        {
          type: "select",
          key: "projectId",
          formItemAttribute: {
            label: "订单编号"
          },
          attributes: {
            placeholder: "请选择订单编号",
            options: projectList.value,
            multiple: false,
            filterable: true,
            clearable: true,
            changeFn: (val: any, origin: any) => {
              const obj = projectList.value.find((item: any) => item.id === val);
              origin.formData.projectName = obj?.code;
              origin.formData.companyId = obj?.companyId;
              origin.formData.companyName = obj?.companyName;
            }
          },
          fieldNames: { label: "code", value: "id" }
        },
        {
          type: "select",
          key: "companyId",
          formItemAttribute: {
            label: "客户名称"
          },
          attributes: {
            placeholder: "请选择客户名称",
            options: companyList,
            multiple: false,
            filterable: true,
            clearable: true,
            disabled: true,
            changeFn: (val: any, origin: any) => {
              const obj = companyList.find(item => item.id === val);
              origin.formData.companyName = obj?.name;
            }
          }
        },

        {
          type: "input",
          key: "agvNums",
          formItemAttribute: {
            label: "AGV数量"
          },
          attributes: {
            placeholder: "请填写AGV数量"
          }
        }
      ]
    },
    {
      type: "group",
      title: "",
      direction: "",
      layout: "grid",
      len: 4,
      list: [
        {
          type: "file",
          key: "applicationFilePath",
          formItemAttribute: {
            label: "RDS申请文件上传"
          },
          attributes: {
            "prefix-data": AUTHORIZE,
            "limit-number": 1,
            accept: "*"
          }
        },
        {
          type: "select",
          key: "authType",
          formItemAttribute: {
            label: "授权类型"
          },
          attributes: {
            placeholder: "请选择授权类型",
            options: authTypeList,
            multiple: false,
            changeFn: (val: any) => {
              if (val === 1) {
                config.value.form.formData.expireTime = "";
                config.value.column[1]["list"][2]["attributes"].disabled = true;
              } else {
                config.value.column[1]["list"][2]["attributes"].disabled = false;
              }
            }
          }
        },
        {
          type: "date-picker",
          key: "expireTime",
          formItemAttribute: {
            label: "授权截止时间"
          },
          attributes: {
            type: "datetime",
            placeholder: "请选择授权截止时间",
            format: "YYYY-MM-DD HH:mm:ss",
            valueFormat: "YYYY-MM-DD HH:mm:ss",
            disabled: config.value.form.formData.authType === 1
          }
        }
      ]
    },
    {
      type: "slot",
      key: "featureList",
      formItemAttribute: {
        label: "功能列表"
      },
      attributes: {}
    }
  ];
  config.value.api = addCompanyAuthorize;
  config.value.transformData = data => {
    data.applicationFilePath = data.applicationFilePath[0].path;
    data.featureList = data.featureList.filter(item => !defaultFeature.includes(item));
    delete data.authType;
    return data;
  };
  config.value.message = "添加成功";
};
const editAgvFn = (row: any) => {
  row = JSON.parse(JSON.stringify(row));
  drawerVisible.value = true;
  config.value.title = "编辑授权";
  config.value.show = false;
  config.value.form = {
    formData: {
      ...row,
      licenseName: row.licenseName,
      companyId: row.companyId,
      companyName: row.companyName,
      projectId: row.projectId,
      projectName: row.projectName,
      agvNums: row.agvNums,
      expireTime: row.expireTime,
      featureList: defaultFeature.concat(row.featureList || []),
      authType: row.expireTime ? 2 : 1
    },
    rules: {
      licenseName: [{ required: true, message: "请填写授权名称" }]
    }
  };
  config.value.column = [
    {
      type: "group",
      title: "",
      direction: "",
      list: [
        {
          type: "input",
          key: "licenseName",
          formItemAttribute: {
            label: "授权名称"
          },
          attributes: {
            placeholder: "请填写授权名称"
          }
        },
        {
          type: "select",
          key: "projectId",
          formItemAttribute: {
            label: "订单编号"
          },
          attributes: {
            placeholder: "请选择订单编号",
            options: projectList.value,
            multiple: false,
            filterable: true,
            clearable: true,
            changeFn: (val: any, origin: any) => {
              const obj = projectList.value.find(item => item.id === val);
              origin.formData.projectName = obj?.name;
            }
          }
        },
        {
          type: "select",
          key: "companyId",
          formItemAttribute: {
            label: "客户名称"
          },
          attributes: {
            placeholder: "请选择客户名称",
            options: companyList,
            multiple: false,
            filterable: true,
            clearable: true,
            changeFn: (val: any, origin: any) => {
              const obj = companyList.find(item => item.id === val);
              origin.formData.companyName = obj?.name;
            }
          }
        },

        {
          type: "input",
          key: "agvNums",
          formItemAttribute: {
            label: "AGV数量"
          },
          attributes: {
            placeholder: "请填写AGV数量"
          }
        }
      ]
    },
    {
      type: "group",
      title: "",
      direction: "",
      layout: "grid",
      len: 4,
      list: [
        {
          type: "select",
          key: "authType",
          formItemAttribute: {
            label: "授权类型"
          },
          attributes: {
            placeholder: "请选择授权类型",
            options: authTypeList,
            multiple: false,
            changeFn: (val: any) => {
              if (val === 1) {
                config.value.form.formData.expireTime = "";
                config.value.column[1]["list"][1]["attributes"].disabled = true;
              } else {
                config.value.column[1]["list"][1]["attributes"].disabled = false;
              }
            }
          }
        },
        {
          type: "date-picker",
          key: "expireTime",
          formItemAttribute: {
            label: "授权截止时间"
          },
          attributes: {
            type: "datetime",
            placeholder: "请选择授权截止时间",
            format: "YYYY-MM-DD HH:mm:ss",
            valueFormat: "YYYY-MM-DD HH:mm:ss",
            disabled: config.value.form.formData.authType === 1
          }
        }
      ]
    },
    {
      type: "slot",
      key: "featureList",
      formItemAttribute: {
        label: "功能列表"
      },
      attributes: {}
    }
  ];
  config.value.api = updateCompanyAuthorize;
  config.value.transformData = data => {
    data.featureList = data.featureList.filter(item => !defaultFeature.includes(item));
    delete data.authType;
    return data;
  };
  config.value.message = "编辑成功";
};

const detailAuthFn = async (row: any) => {
  drawerVisible.value = true;
  config.value.title = "查看详情";
  config.value.show = true;
  const { data } = await getCompanyAuthorizeDetail({ id: row });
  config.value.column = [
    {
      type: "group",
      title: "授权信息",
      direction: "",
      layout: "grid",
      len: 4,
      list: [
        {
          title: "授权名称",
          value: data.licenseName || "--"
        },
        {
          title: "客户名称",
          value: data.companyName || "--"
        },
        {
          title: "订单编号",
          value: data.projectName || "--"
        },
        {
          title: "AGV数量",
          value: data.agvNums || "--"
        },
        {
          title: "产品许可",
          value: defaultFeature.concat(data.featureList).join(",") || "--"
        },
        {
          title: "授权类型",
          value: data.expireTime ? "非永久" : "永久"
        },
        {
          title: "签发时间",
          value: data.gmtCreate || "--"
        },
        {
          title: "到期时间",
          value: data.expireTime || "--"
        }
      ]
    },
    {
      type: "group",
      title: "硬件信息",
      direction: "",
      layout: "grid",
      len: 4,
      list: [
        {
          title: "序列号（主板或CPU等）",
          value: data.serialNumber || "--"
        },
        {
          title: "硬件ID",
          value: data.hardwareId || "--"
        },
        {
          title: "网卡MAC地址",
          value: (data.macAddrList && data.macAddrList.join(",")) || "--"
        }
      ]
    }
  ];
};
const refresh = () => {
  proTable.value?.getTableList();
};
const sortChange = (val: any) => {
  const { order, prop } = val;
  sortOptions.value = { sortFiled: prop, sortType: order === "ascending" ?? undefined };
  refresh();
};
onMounted(async () => {
  getListAllUserFn();
  getCompanyListFn();
  getProject();
});
</script>
<style lang="scss" scoped>
.summary-left-project {
  margin-top: 10px;
  background: #ffffff;
  .project-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 72px;
    padding: 0 30px;
    span:first-child {
      font-size: 16px;
      font-weight: 600;
      color: #333333;
    }
    span:last-child {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-weight: 600;
      color: #333333;
      cursor: pointer;
      i:first-child {
        width: 15px;
        height: 15px;
        margin-right: 10px;
        font-size: 15px;
        color: #666666;
      }
    }
  }
  .project-content {
    .user-wrap {
      display: flex;
      align-items: center;
      img {
        width: 32px;
        height: 32px;
        margin-right: 10px;
        border-radius: 50%;
      }
      span:last-child {
        font-size: 14px;
        font-weight: 400;
        color: #333333;
      }
    }
  }
  .project-content-wrap {
    padding: 0 30px 20px;
    .project-content-item {
      display: flex;
      flex-flow: column nowrap;
      .title {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #999999;
      }
      .fontWeight {
        font-size: 16px;
      }
      .content {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #333333;
      }
    }
  }
  .empty-box {
    padding: 0 30px 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
    text-align: center;
  }
  .el-button-btn {
    margin-top: 20px;
  }
}

.red {
  color: red;
}
</style>
<style>
.dialog-form-custom {
  .upload-box-s {
    border-radius: 0 !important;
    .upload {
      border-radius: 0 !important;
      .el-upload {
        height: 100%;
        border-radius: 0 !important;
      }
    }
  }
  .upload-flex {
    display: flex;
    align-items: center;
    height: 100%;
    cursor: pointer;
    .el-input {
      margin-right: 10px;
    }
    .el-button {
      width: 32px;
      height: 32px;
      border-radius: 0 !important;
    }
  }
  .el-dialog__body {
    padding-bottom: 20px;
  }
}
</style>
